{% extends "templates/main_template.html.j2" %}

{% import "macros/issues_table.html.j2" as ISSUES_TABLE %}
{% import "macros/file_input.html.j2" as FILE_INPUT %}
{% import "macros/issue_field.html.j2" as ISSUE_FIELD %}
{% import "macros/markdown_textarea.html.j2" as MARKDOWN_TEXTAREA %}
{% import "macros/tab_switcher.html.j2" as TAB_SWITCHER %}
{% import "macros/switch.html.j2" as SWITCH %}
{% import "macros/diff_table.html.j2" as DIFF_TABLE %}
{% import "macros/select_options.html.j2" as SELECT_OPTIONS %}
{% import "macros/modal_confirmation.html.j2" as CONFIRMATION %}
{% import "macros/user_name.html.j2" as USER_NAME %}

{% set active_menu = 'issues' %}
{% set issue_statistics_helper = project_manager.issue_statistics_helper %}
{% set value_types = project_manager.value_types() %}
{% set sub_issues = project_manager.sub_issues(target_issue.id)%}
{% set project = project_manager.project(target_issue.project_id)%}
{% set issue_kind = project_manager.issue_kind(target_issue.issue_kind_id) %}
{% set more_comments = project_manager.issues_sub_issues_comments(target_issue.id) %}
{% set tab_menu = [
  ['Описание', 'about'],
  ['Дочерние запросы [' + sub_issues|length|string + ']', 'kids'],
  ['Комментарии [' + target_issue.comments|length|string + ']' , 'comments'],
  ['Комментарии с дочерними [' + more_comments|length|string + ']' , 'more_comments'],
  ['История изменений [' + target_issue.changes|length|string + ']', 'history'],
  ['Статистика', 'statistics'],
] %}

{% block title -%}
  {{ issue_kind.caption|e }} #{{ target_issue.id -}}
  : {{ target_issue.caption|e }} · Запрос · Farado
{%- endblock %}

{#----------------------------------------------------------------------------#}
{% block styles %}
  {{ ISSUES_TABLE.STYLES() }}
  <link href="/static/css/page-toolbar.css" rel="stylesheet" type="text/css" />
  <link href="/static/css/breadcrumbs.css" rel="stylesheet" type="text/css" />
  {{ FILE_INPUT.STYLES() }}
  {{ SELECT_OPTIONS.STYLES() }}
  {{ MARKDOWN_TEXTAREA.STYLES() }}
  <style>
    .issue_field_table th {
      white-space: nowrap;
    }
  </style>
{% endblock %}


{#----------------------------------------------------------------------------#}
{% block breadcrumb %}
    {% if project %}
      <div class="breadcrumb-wrap">
        <span class="sep"><i class="bi bi-chevron-right"></i></span>
          <span class="breadcrumb-text">
            <a href="/projects/project/{{ project.id }}">
              {{ project.caption|e }}
            </a>
          </span>
      </div>
    {% endif %}

    {% for parent_issue in project_manager.parent_issues(target_issue.parent_id) | reverse %}
      <div class="breadcrumb-wrap">
        <span class="sep"><i class="bi bi-chevron-right"></i></span>
          <span class="breadcrumb-text">
            <a href="/issues/issue/{{ parent_issue.id }}">
              {{ project_manager.issue_kind(parent_issue.issue_kind_id).caption|e }}
              #{{ parent_issue.id }}: {{ parent_issue.caption|e }}
            </a>
        </span>
      </div>
    {% endfor %}

    <div class="breadcrumb-wrap active" aria-current="page">
      <span class="sep"><i class="bi bi-chevron-right"></i></span>
        <span class="breadcrumb-text">
          {{ project_manager.issue_kind(target_issue.issue_kind_id).caption|e }}
          #{{ target_issue.id }}: {{ target_issue.caption|e }}
        </span>
    </div>
{% endblock %}

{#----------------------------------------------------------------------------#}
{# Таб 1 — Описание #}
{% block tab_content_1 %}
  <div class="page-toolbar">
    <div class="d-flex justify-content-between align-items-center container-button">
      <div class="d-flex align-items-center container-button">
        <h5 title="{{ target_issue.caption|e }}">
          {{ project_manager.issue_kind(target_issue.issue_kind_id).caption|e }}
          #{{ target_issue.id }}: {{ target_issue.caption|e }}
        </h5>

        {# Индикация — над запросом ведутся работы #}
          {% set is_active = issue_statistics_helper.is_active_issue(target_issue) %}
          {% if is_active %}
            <i class="bi bi-hammer ms-1"
                title="Ведутся работы, запрос(ы) в активных состояниях.">
            </i>
          {% endif %}
        {# /Индикация — над запросом ведутся работы #}
      </div>
    </div>
  </div>

  {# Прогресс запроса #}
    <div>
      <div class="progress">
        {% set progress = project_manager.progress_value(target_issue.id) %}
        <div
            class="progress-bar
              {%- if 100 == progress %} bg-success
              {%- elif 40 > progress %} bg-warning
              {%- endif %}"
            role="progressbar"
            style="width: {{ progress }}%;"
            aria-valuenow="{{ progress }}"
            aria-valuemin="0"
            aria-valuemax="100">{{ progress }}%</div>
      </div>
    </div>
  {# /Прогресс запроса #}

  <div class="row">
    {# -- Элемент управления состоянием запроса -- #}
      <div class="col mt-2">
        {% set state = project_manager.state(target_issue.state_id) %}
        <button
            class="btn btn-outline-primary btn-sm dropdown-toggle"
            type="button"
            id="dropdownMenuState"
            data-bs-toggle="dropdown"
            aria-expanded="false">
          {{ state.caption|e if state is not none else '—' }}
          <i class="bi bi-caret-down-fill"></i>
        </button>
        <ul class="dropdown-menu" aria-labelledby="dropdownMenuState">
          {% for state in project_manager.new_states_for_issue(target_issue) %}
            <li>
              <a  class="dropdown-item"
                  href="/issues/issue/{{ target_issue.id -}}?issue_state_id={{ state.id -}}">
                {{- state.caption|e -}}
              </a>
            </li>
          {% endfor %}
        </ul>
      </div>
    {# -- /Элемент управления состоянием запроса -- #}

    {# -- Переключатель режима просмотра/изменения запроса (issue) -- #}
      <div class="col">
        <ul class="nav nav-pills mb-3 justify-content-end" id="pillsTab" role="tablist">
          <li class="nav-item" role="presentation" id="view_button_place">
            <button
                class="nav-link active"
                id="pills-view-tab"
                data-bs-toggle="pill"
                data-bs-target="#pills-view"
                type="button"
                role="tab"
                aria-controls="pills-view"
                aria-selected="true">Просмотр</button>
          </li>
          <li class="nav-item" role="presentation">
            <button
                class="nav-link {% if not restriction.is_save_enabled %}disabled{% endif %}"
                id="pills-edit-tab"
                data-bs-toggle="pill"
                data-bs-target="#pills-edit"
                type="button"
                role="tab"
                aria-controls="pills-edit"
                {% if not restriction.is_save_enabled %}disabled{% endif %}
                aria-selected="false">Редактор</button>
          </li>
        </ul>
      </div>
      <script>
        document_ready_functions.push(function() {
          {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('pillsTab') }}
        });
      </script>
    {# -- /Переключатель режима просмотра/изменения запроса (issue) -- #}
  </div>

  <div class="row placeholders issue-content">
    <div class="tab-content" id="pillsTabContent">

      {# -- Просмотр данных запроса (issue) -- #}
        <div
            class="tab-pane fade show active"
            id="pills-view"
            role="tabpanel"
            aria-labelledby="pills-view-tab">

          {# -- Контент запроса -- #}
            <div class="col-12 mb-4">
              <div id="contentView"
                  class="comment-link markdown_result_container"></div>
            </div>
          {# -- /Контент запроса -- #}

          {# -- Перечень полей и значений -- #}
            <div class="col-12">
              <table class="table table-striped table-bordered issue_field_table">
                <thead class="thead-dark">
                  <tr>
                    <th scope="col" style="width: 2%">Поле</th>
                    <th scope="col">Значение</th>
                  </tr>
                </thead>
                <tbody>

                  {# Когда создан #}
                    <tr>
                      <th>
                        Когда создан
                      </th>
                      <td>
                        {{ target_issue.created() }}
                      </td>
                    </tr>
                  {# /Когда создан #}

                  {# Версия #}
                    {% set version = project_manager.version(target_issue.version_id) %}
                    {% if version %}
                      <tr>
                        <th>
                          Версия
                        </th>
                        <td>
                          <a href="/projects/version/{{ version.id }}">{{ version.caption|e }}</a>
                        </td>
                      </tr>
                    {% endif %}
                  {# /Версия #}

                  {# Кем создан #}
                    {% set create_user = project_manager.user(target_issue.create_user_id()) %}
                    {% if create_user %}
                      <tr>
                        <th>
                          Кем создан
                        </th>
                        <td>
                          <a href="/users/user_statistics/{{ create_user.id }}">
                            {{ USER_NAME.VALUE_WITH_ICON(create_user, user.id) }}
                          </a>
                        </td>
                      </tr>
                    {% endif %}
                  {# /Кем создан #}

                  {# Состояние запроса #}
                    <tr>
                      <th>
                        Состояние
                      </th>
                      <td>
                        {{ state.caption|e if state is not none else '—' }}
                      </td>
                    </tr>
                  {# /Состояние запроса #}

                  {# Настраиваемые поля #}
                    {% for field in target_issue.fields %}
                      {% set field_kind = project_manager.field_kind(field.field_kind_id) %}
                      {% if field_kind %}
                        <tr>
                          <th title="Тип поля #{{ field.field_kind_id }}">
                            {{ field_kind.caption|e }}
                          </th>
                          <td>
                            {{ ISSUE_FIELD.TAG(
                                field,
                                field_kind,
                                project_manager,
                                value_types,
                                user.id )
                            }}
                          </td>
                        </tr>
                      {% endif %}
                    {% endfor %}
                  {# /Настраиваемые поля #}

                  {# Когда изменён #}
                    <tr>
                      <th>
                        Когда изменён
                      </th>
                      <td>
                        {{ target_issue.last_modified() }}
                      </td>
                    </tr>
                  {# /Когда изменён #}

                  {# Кем изменён #}
                    {% set last_modify_user = project_manager.user(target_issue.last_modify_user_id()) %}
                    {% if last_modify_user %}
                      <tr>
                        <th>
                          Кем изменён
                        </th>
                        <td>
                          <a href="/users/user_statistics/{{ last_modify_user.id }}">
                            {{ USER_NAME.VALUE_WITH_ICON(last_modify_user, user.id) }}
                          </a>
                        </td>
                      </tr>
                    {% endif %}
                  {# /Кем изменён #}

                </tbody>
              </table>
            </div>
          {# -- Перечень полей и значений -- #}

          {# -- Вложенные файлы -- #}
            {% if target_issue.files %}
              {{ FILE_INPUT.INPUT('issue_files') }}
              <script>
                document_ready_functions.push(function() {
                  $("#issue_files").fileinput({
                    previewFileType: 'any',
                    language: 'ru',
                    overwriteInitial: false,
                    showUpload: false,
                    showBrowse: false,
                    showRemove: false,
                    dropZoneEnabled: false,
                    showDownload: true,
                    showClose: false,
                    initialPreviewShowDelete: false,
                    initialPreviewDownloadUrl: "/issues/file/{{ target_issue.id }}",
                    initialPreview: [
                      {% for file in target_issue.files -%}
                        "/issues/file/{{ target_issue.id }}?file_id={{ file.id }}",
                      {%- endfor %}
                    ],
                    initialPreviewConfig: [
                      {% for file in target_issue.files -%}
                        {
                          {% set file_type = project_manager.file_manager.file_type(file.caption) %}
                          caption: "{{ file.caption|e }}",
                          size: {{ project_manager.file_manager.file_size(file) }},
                          type: "{{ file_type }}",
                          previewAsData: {% if 'image' == file_type %}true{% else %}false{% endif %},
                          key: {{ file.id }}
                        },
                      {%- endfor %}
                    ]
                  });
                });
              </script>
            {% endif %}
          {# -- /Вложенные файлы -- #}

        </div>
      {# -- /Просмотр данных запроса (issue) -- #}

      {# -- Изменение данных запроса (issue) -- #}
        <div
            class="tab-pane fade"
            id="pills-edit"
            role="tabpanel"
            aria-labelledby="pills-edit-tab">

          <form class="row g-3" action="/issues/issue/{{ target_issue.id }}" method="post">
            {# -- Проект -- #}
              <div class="col-md-6">
                <label for="issue_project_id" class="form-label">Проект</label>
                {{ SELECT_OPTIONS.INPUT_SINGLE(
                    data_source = 'projects',
                    name = 'issue_project_id',
                    project_manager = project_manager,
                    selected_id = target_issue.project_id)
                }}
              </div>
            {# -- /Проект -- #}

            {# -- Версия -- #}
              <div class="col-md-3">
                <label for="issue_version_id" class="form-label">Версия</label>
                {{ SELECT_OPTIONS.INPUT_SINGLE(
                    data_source = 'projects_versions',
                    name = 'issue_version_id',
                    project_manager = project_manager,
                    selected_id = target_issue.version_id )
                }}
              </div>
            {# -- /Версия -- #}

            {# -- Родительский запрос -- #}
              <div class="col-md-3">
                <label for="inputCaption" class="form-label">Идентификатор родителя</label>
                <input
                    type="number"
                    name="issue_parent_id"
                    class="form-control"
                    id="inputCaption"
                    value="{{ target_issue.parent_id }}">
              </div>
            {# -- /Родительский запрос -- #}

            {# -- Наименование -- #}
              <div class="col-12">
                <label for="inputCaption" class="form-label">Наименование</label>
                <input
                    type="text"
                    name="issue_caption"
                    class="form-control"
                    id="inputCaption"
                    value="{{ target_issue.caption|e }}" required>
              </div>
            {# -- /Наименование -- #}

            {# -- Описание -- #}
              <div class="col-12 issue-content">
                <label for="contentTab" class="form-label">Описание</label>
                {{ MARKDOWN_TEXTAREA.INPUT(
                      'contentTab',
                      'issue_content_result',
                      'issue_content',
                      project_manager.safe_value(target_issue.content) )
                }}
                <script>
                  document_ready_functions.push(function() {
                    {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('contentTab') }}
                    markdownToHtml('issue_content', 'issue_content_result');
                    markdownToHtml('issue_content', 'contentView');
                  });
                </script>
              </div>
            {# -- /Описание -- #}

            <hr/>

            {# -- Issue.fields -- #}
              {% for field in target_issue.fields %}
                <div class="col-12">
                  {% set field_kind = project_manager.field_kind(field.field_kind_id) %}
                  {% if field_kind %}
                    <div class="form-group row">
                      <label
                          for="inputField_{{ field_kind.id }}"
                          class="col-sm-2 col-form-label">{{ field_kind.caption|e }}</label>

                      <div class="col-sm-10 issue-content">
                        {% if value_types.string == field_kind.value_type %}
                          {# Строка #}
                          <input
                              type="text"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value|e }}">

                        {% elif value_types.markdown_text == field_kind.value_type %}
                          {# Текст markdown #}
                          {{ MARKDOWN_TEXTAREA.INPUT(
                              tab_id = 'inputField_' + field_kind.id | string + '',
                              result_id = 'field_kind_' + field_kind.id | string + '_result',
                              field_name = 'field_kind_' + field_kind.id | string,
                              field_value = field.value|e )
                          }}
                          <script>
                            document_ready_functions.push(function() {
                              {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT(
                                  'inputField_' + field_kind.id | string )
                              }};
                              markdownToHtml(
                                  'field_kind_{{ field_kind.id }}',
                                  'field_kind_{{ field_kind.id }}_result');
                              markdownToHtml(
                                  'field_kind_{{ field_kind.id }}',
                                  'field_kind_{{ field_kind.id }}_view');
                            });
                          </script>

                        {% elif value_types.integer == field_kind.value_type %}
                          {# Целое число #}
                          <input
                              type="number"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value }}">

                        {% elif value_types.float == field_kind.value_type %}
                          {# Дробное число #}
                          <input
                              type="number"
                              step="any"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value }}">

                        {% elif value_types.bool == field_kind.value_type %}
                          {# Флаг #}
                          <div class="form-check form-switch">
                            {{ SWITCH.INPUT(
                                id = 'field_kind_' + field_kind.id|string,
                                name = 'field_kind_' + field_kind.id|string,
                                is_checked = field.value )
                            }}
                          </div>

                        {% elif value_types.date_time == field_kind.value_type %}
                          {# Дата/время #}
                          <input
                              type="datetime-local"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value|e }}">

                        {% elif value_types.uri == field_kind.value_type %}
                          {# Ссылка #}
                          <input
                              type="url"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value|e }}">

                        {% elif value_types.select == field_kind.value_type %}
                          {# Выпадающий список (единичный) #}
                          {{ SELECT_OPTIONS.INPUT_SINGLE(
                              data_source = 'field_kind_select',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_id = field.value,
                              data_source_id = field_kind.id)
                          }}

                        {% elif value_types.select_multi == field_kind.value_type %}
                          {# Выпадающий список (множественный) #}
                          {{ SELECT_OPTIONS.INPUT_MULTY(
                              data_source = 'field_kind_select',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_ids = field.value_as_list(),
                              data_source_id = field_kind.id)
                          }}

                        {% elif value_types.issue_id == field_kind.value_type %}
                          {# Запрос (issue) #}
                          {# TODO : Решить вопрос поиска необходимого запроса
                                    через ui #}
                          <input
                              type="number"
                              name="field_kind_{{ field_kind.id }}"
                              class="form-control"
                              id="inputField_{{ field_kind.id }}"
                              value="{{ field.value|e }}">

                        {% elif value_types.user_id == field_kind.value_type %}
                          {# Пользователь #}
                          {{ SELECT_OPTIONS.INPUT_SINGLE(
                              data_source = 'users',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_id = field.value,
                              data_source_id = user.id)
                          }}

                        {% elif value_types.project_id == field_kind.value_type %}
                          {# Проект #}
                          {{ SELECT_OPTIONS.INPUT_SINGLE(
                              data_source = 'projects',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_id = field.value)
                          }}

                        {% elif value_types.version_id == field_kind.value_type %}
                          {# Версия #}
                          {{ SELECT_OPTIONS.INPUT_SINGLE(
                              data_source = 'projects_versions',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_id = field.value)
                          }}

                        {% elif value_types.users_ids == field_kind.value_type %}
                          {# Перечень пользователей #}
                          {{ SELECT_OPTIONS.INPUT_MULTY(
                              data_source = 'users',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_ids = field.value_as_ids(),
                              data_source_id = user.id)
                          }}

                        {% elif value_types.projects_ids == field_kind.value_type %}
                          {# Перечень проектов #}
                          {{ SELECT_OPTIONS.INPUT_MULTY(
                              data_source = 'projects',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_ids = field.value_as_ids())
                          }}

                        {% elif value_types.versions_ids == field_kind.value_type %}
                          {# Перечень версий #}
                          {{ SELECT_OPTIONS.INPUT_MULTY(
                              data_source = 'projects_versions',
                              name = 'field_kind_' + field_kind.id|string,
                              project_manager = project_manager,
                              selected_ids = field.value_as_ids())
                          }}
                        {% endif %}
                      </div>
                    </div>
                  {% endif %}
                </div>
              {% endfor %}
            {# -- /Issue.fields -- #}

            {# -- Элементы управления изменением запроса -- #}
              {% if restriction.is_save_enabled %}
                <div class="col-12">
                  <div class="clearfix">
                    {# -- Кнопка: удалить запрос -- #}
                      {{ CONFIRMATION.BUTTON(
                          caption = '<i class="bi bi-trash"></i> Удалить',
                          title = 'Удалить данный запрос',
                          class = 'btn btn-danger ml-3 float-start',
                          target = 'remove_issue_confirmation_'
                              + target_issue.id|string)
                      }}
                      {{ CONFIRMATION.MODAL_WINDOW(
                          title = 'Удаление запроса',
                          text = 'Вы уверены, что хотите навсегда удалить запрос «'
                              + target_issue.caption|e
                              + '»?',
                          action_button_href = '/issues/remove_issue/'
                              + target_issue.id|string,
                          action_button_text = 'Да',
                          window_id = 'remove_issue_confirmation_'
                              + target_issue.id|string)
                      }}
                    {# -- /Кнопка: удалить запрос -- #}

                    {# -- Кнопка: сохранить запрос -- #}
                      <button
                          type="submit"
                          id="saveButton"
                          class="btn btn-success float-end">
                        <i class="bi bi-save"></i> Сохранить
                      </button>
                    {# -- /Кнопка: сохранить запрос -- #}
                  </div>
                </div>
              {% endif %}
            {# -- /Элементы управления изменением запроса -- #}
          </form>

          <hr/>

          <div class="col-12">
            {# -- Issue.files -- #}
              {{ FILE_INPUT.INPUT('issue_files_editor') }}
              <script>
                document_ready_functions.push(function() {
                  $("#issue_files_editor").fileinput({
                    uploadUrl: '/issues/upload/{{ target_issue.id }}',
                    previewFileType: 'any',
                    language: 'ru',
                    overwriteInitial: false,
                    showUpload: true,
                    showDownload: true,
                    initialPreviewDownloadUrl: "/issues/file/{{ target_issue.id }}",
                    deleteUrl: "/issues/remove_file/{{ target_issue.id }}",
                    initialPreview: [
                      {% for file in target_issue.files -%}
                        "/issues/file/{{ target_issue.id }}?file_id={{ file.id }}",
                      {%- endfor %}
                    ],
                    initialPreviewConfig: [
                      {% for file in target_issue.files -%}
                        {
                          {% set file_type = project_manager.file_manager.file_type(file.caption) %}
                          caption: "{{ file.caption|e }}",
                          size: {{ project_manager.file_manager.file_size(file) }},
                          type: "{{ file_type }}",
                          previewAsData: {% if 'image' == file_type %}true{% else %}false{% endif %},
                          key: {{ file.id }}
                        },
                      {%- endfor %}
                    ]
                  });
                  $("#issue_files_editor").on('filedeleted', function(event, key, jqXHR, data) {
                    viewButtonToUpdate();
                  });
                  $('#issue_files_editor').on('fileuploaded', function(event, previewId, index, fileId) {
                    viewButtonToUpdate()
                  });
                });
                // {# HACK: for update FILE_INPUT in view #}
                function viewButtonToUpdate() {
                  $("#view_button_place").html(
                    '<a class="nav-link" href="/issues/issue/{{ target_issue.id }}">Просмотр</a>'
                  );
                };
              </script>
            {# -- /Issue.files -- #}
          </div>

        </div>
      {# -- /Изменение данных запроса (issue) -- #}

    </div>
  </div>

{% endblock tab_content_1 %}


{#----------------------------------------------------------------------------#}
{# Таб 2 — Дочерние запросы #}
{% block tab_content_2 %}
  {# -- Элементы управления дочерними запросами -- #}
    <div class="page-toolbar">
      <div class="btn-group" role="group" aria-label="Additional issue modification tools">
        {% if restriction.is_create_enabled %}
          <button
              class="btn btn-outline-primary btn-sm dropdown-toggle"
              type="button"
              id="dropdownMenuAddIssue"
              data-bs-toggle="dropdown"
              aria-expanded="false">Создать дочерний запрос <i class="bi bi-caret-down-fill"></i></button>
          <ul class="dropdown-menu" aria-labelledby="dropdownMenuAddIssue">
            {% for issue_kind in project_manager.issue_kinds() %}
              {% set workflow = project_manager.workflow(issue_kind.workflow_id) %}
              <li>
                <a  class="dropdown-item"
                    href="/issues/add_issue?issue_kind_id={{ issue_kind.id -}}
                      &parent_id={{ target_issue.id -}}
                      &project_id={{ target_issue.project_id }}">
                  {{- workflow.caption|e }}: {{ issue_kind.caption|e -}}
                </a>
              </li>
            {% endfor %}
          </ul>
        {% endif %}
      </div>
    </div>
  {# -- /Элементы управления дочерними запросами -- #}

  {# -- Таблица дочерних запросов -- #}
    <div class="col-12 mt-2">
      {{ ISSUES_TABLE.TAG(
          columns,
          column_helper,
          issues_table="sub_issues_table")
      }}

      <script>
        document_ready_functions.push(function() {

          {{ ISSUES_TABLE.DOCUMENT_READY_SCRIPT(
              columns,
              column_helper,
              var_name="sub_issues_table",
              issues_table="sub_issues_table",
              url="/issues/issues_data/" + target_issue.id | string)
          }}

          // Корректировка ширины столбцов таблицы дочерних запросов
          // при переходе на соответствующий таб
          $('button[data-bs-target="#kids"]').on('shown.bs.tab', function (event) {
            sub_issues_table.columns.adjust().draw();
          });
        });
      </script>
    </div>
  {# -- /Таблица дочерних запросов -- #}
{% endblock tab_content_2 %}


{#----------------------------------------------------------------------------#}
{# Таб 3 — Комментарии #}
{% block tab_content_3 %}
  <div class="row mt-3">
    {# -- Перечень комментариев -- #}
      <div class="col-12">
        {% for comment in target_issue.ordered_comments() %}
          <div class="card mb-4">
            <div class="card-header">
              <div class="row align-items-center">
                <div class="col">
                  {% set comment_user = project_manager.user_by_id(comment.user_id) %}
                  {% if comment_user %}
                    <a href="/users/user_statistics/{{ comment_user.id }}">
                      {{ USER_NAME.VALUE_WITH_ICON(comment_user, user.id) }}
                    </a>
                  {% endif %}
                </div>
                <div class="col text-end">
                  {{ comment.formated_creation_datetime() }}
                  {% if restriction.is_delete_enabled or
                        (
                          restriction.is_save_enabled and
                          comment.user_id == user.id
                        )
                  %}
                    {{ CONFIRMATION.BUTTON(
                        caption = '<i class="bi bi-trash trash-icon"></i>',
                        title = 'Удалить комментарий',
                        class = 'btn btn-light btn-sm ml-3',
                        target = 'remove_comment_confirmation_' + comment.id|string)
                    }}
                    {{ CONFIRMATION.MODAL_WINDOW(
                        title = 'Удаление комментария',
                        text = 'Вы уверены, что хотите навсегда удалить комментарий?',
                        action_button_href = '/issues/remove_comment/'
                            + target_issue.id|string + '/' + comment.id|string,
                        action_button_text = 'Да',
                        window_id = 'remove_comment_confirmation_' + comment.id|string)
                    }}
                  {% endif %}
                </div>
              </div>
            </div>
            <div class="card-body">
              <p class="card-text comment-link markdown_result_container"
                  id="comment_{{ comment.id }}_result"></p>
              <textarea
                  style="display:none;"
                  id="comment_{{ comment.id }}">
                {{- project_manager.safe_value(comment.content) -}}
              </textarea>
              <script>
                document_ready_functions.push(function() {
                  markdownToHtml(
                    'comment_{{ comment.id }}',
                    'comment_{{ comment.id }}_result');
                });
              </script>
              <script>
                $(document).ready(function(){
                  $('[data-toggle="tooltip"]').tooltip();
                });
              </script>
              {% if comment.files %}
                <input
                    id="comment_{{ comment.id }}_files"
                    name="comment_{{ comment.id }}_files"
                    type="file" class="file">
                <script>
                  document_ready_functions.push(function() {
                    $("#comment_{{ comment.id }}_files").fileinput({
                        showUpload: false,
                        dropZoneEnabled: false,
                        language: 'ru',
                        inputGroupClass: "input-group-sm",
                        previewFileType: 'any',
                        overwriteInitial: false,
                        showUpload: false,
                        showBrowse: false,
                        showRemove: false,
                        showDownload: true,
                        showUploadStats: false,
                        showClose: false,
                        initialPreviewShowDelete: false,
                        initialPreviewDownloadUrl: "/issues/file/{{ target_issue.id }}",
                        initialPreview: [
                          {% for file in comment.files -%}
                            "/issues/file/{{ target_issue.id }}?file_id={{ file.id }}",
                          {%- endfor %}
                        ],
                        initialPreviewConfig: [
                          {% for file in comment.files -%}
                            {
                              {% set file_type = project_manager.file_manager.file_type(file.caption) %}
                              caption: "{{ file.caption|e }}",
                              size: {{ project_manager.file_manager.file_size(file) }},
                              type: "{{ file_type }}",
                              previewAsData: {% if 'image' == file_type %}true{% else %}false{% endif %},
                              key: {{ file.id }}
                            },
                          {%- endfor %}
                        ]
                    });
                  });
                </script>
              {% endif %}
            </div>
          </div>
        {% endfor %}
      </div>
    {# -- /Перечень комментариев -- #}

    {# -- Элементы управления: добавить новый комментарий -- #}
      {% if restriction.is_save_enabled %}
        <form class="row g-3"
            action="/issues/add_comment/{{ target_issue.id }}"
            method="post"
            enctype="multipart/form-data">
          <div class="col-12 issue-content">
            {# Поле ввода нового комментария #}
              {{ MARKDOWN_TEXTAREA.INPUT(
                  tab_id = 'newCommentTab',
                  result_id = 'new_comment_result',
                  field_name = 'new_comment_value',
                  is_required = True)
              }}
              <script>
                document_ready_functions.push(function() {
                  {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('newCommentTab') }}
                  markdownToHtml('new_comment_value', 'new_comment_result');
                });
              </script>
            {# /Поле ввода нового комментария #}

            {# Поле ввода вложенных файлов #}
              <div class="file-loading"> 
                <input
                    id="new_comment_files"
                    name="new_comment_files"
                    type="file"
                    multiple>
              </div>
              <script>
                document_ready_functions.push(function() {
                  $("#new_comment_files").fileinput({
                      showUpload: false,
                      dropZoneEnabled: false,
                      maxFileCount: 10,
                      language: 'ru',
                      inputGroupClass: "input-group-sm"
                  });
                });
              </script>
            {# /Поле ввода вложенных файлов #}
          </div>
          <div class="col-12">
            <div class="button-container">
              <button
                  class="btn btn-success"
                  type="submit">
                <i class="bi bi-pen"></i>
                Новый комментарий
              </button>
            </div>
          </div>
        </form>
      {% endif %}
    {# -- /Элементы управления: добавить новый комментарий -- #}
  </div>
{% endblock tab_content_3 %}


{#----------------------------------------------------------------------------#}
{# Таб 4 — Комментарии с дочерними #}
{% block tab_content_4 %}
  <div class="row mt-3">
    {# -- Перечень комментариев -- #}
      <div class="col-12">
        {% for comment in more_comments %}
          {% set is_current_issue = target_issue.id == comment.issue_id %}
          {% if is_current_issue %}
            {% set issue = target_issue %}
          {% else %}
            {% set issue = project_manager.issue(comment.issue_id) %}
            {% if not issue %}{% continue %}{% endif %}
          {% endif %}

          <div class="card mb-4">
            <div class="card-header">
              <div class="row align-items-center">
                {# -- Пользователь -- #}
                  <div class="col">
                    {% set comment_user = project_manager.user_by_id(comment.user_id) %}
                    {% if comment_user %}
                      <a href="/users/user_statistics/{{ comment_user.id }}">
                        {{ USER_NAME.VALUE_WITH_ICON(comment_user, user.id) }}
                      </a>
                    {% endif %}
                  </div>
                {# -- /Пользователь -- #}

                {# -- Запрос -- #}
                  <div class="col text-center">
                    {% if is_current_issue %}
                      <small>Текущий запрос</small>
                    {% else %}
                      <a href="/issues/issue/{{ issue.id }}">
                        <i class="bi bi-card-heading"></i>
                        {{ project_manager.issue_kind(issue.issue_kind_id).caption|e }}
                        #{{ issue.id }}: {{ issue.caption|e }}
                      </a>
                    {% endif %}
                  </div>
                {# -- /Запрос -- #}

                {# -- Дата и время -- #}
                  <div class="col text-end">
                    {{ comment.formated_creation_datetime() }}
                  </div>
                {# -- /Дата и время -- #}
              </div>
            </div>
            <div class="card-body">
              <p class="card-text comment-link markdown_result_container"
                  id="more_comment_{{ comment.id }}_result"></p>
              <textarea
                  style="display:none;"
                  id="more_comment_{{ comment.id }}">
                {{- project_manager.safe_value(comment.content) -}}
              </textarea>
              <script>
                document_ready_functions.push(function() {
                  markdownToHtml(
                    'more_comment_{{ comment.id }}',
                    'more_comment_{{ comment.id }}_result');
                });
              </script>
              <script>
                $(document).ready(function(){
                  $('[data-toggle="tooltip"]').tooltip();
                });
              </script>
              {% if comment.files %}
                <input
                    id="more_comment_{{ comment.id }}_files"
                    name="more_comment_{{ comment.id }}_files"
                    type="file" class="file">
                <script>
                  document_ready_functions.push(function() {
                    $("#more_comment_{{ comment.id }}_files").fileinput({
                        showUpload: false,
                        dropZoneEnabled: false,
                        language: 'ru',
                        inputGroupClass: "input-group-sm",
                        previewFileType: 'any',
                        overwriteInitial: false,
                        showUpload: false,
                        showBrowse: false,
                        showRemove: false,
                        showDownload: true,
                        showUploadStats: false,
                        showClose: false,
                        initialPreviewShowDelete: false,
                        initialPreviewDownloadUrl: "/issues/file/{{ issue.id }}",
                        initialPreview: [
                          {% for file in comment.files -%}
                            "/issues/file/{{ issue.id }}?file_id={{ file.id }}",
                          {%- endfor %}
                        ],
                        initialPreviewConfig: [
                          {% for file in comment.files -%}
                            {
                              {% set file_type = project_manager.file_manager.file_type(file.caption) %}
                              caption: "{{ file.caption|e }}",
                              size: {{ project_manager.file_manager.file_size(file) }},
                              type: "{{ file_type }}",
                              previewAsData: {% if 'image' == file_type %}true{% else %}false{% endif %},
                              key: {{ file.id }}
                            },
                          {%- endfor %}
                        ]
                    });
                  });
                </script>
              {% endif %}
            </div>
          </div>
        {% endfor %}
      </div>
    {# -- /Перечень комментариев -- #}
  </div>
{% endblock tab_content_4 %}


{#----------------------------------------------------------------------------#}
{# Таб 5 — История изменений #}
{% block tab_content_5 %}
  <div class="row mt-3">
    {# -- Перечень изменений запроса -- #}
      <div class="col-12">
        {% for change in target_issue.ordered_changes() %}
          <div class="card mb-3">
            <div class="card-header">
              <div class="row">
                <div class="col">
                  {% set change_user = project_manager.user_by_id(change.user_id) %}
                  {% if change_user %}
                    <a href="/users/user_statistics/{{ change_user.id }}">
                      {{ USER_NAME.VALUE_WITH_ICON(change_user, user.id) }}
                    </a>
                  {% endif %}
                </div>
                <div class="col text-end">
                  {{ change.formated_date_time() }}
                </div>
              </div>
            </div>
            {{ DIFF_TABLE.TAG(
                change,
                project_manager)
            }}
          </div>
        {% endfor %}
      </div>
    {# -- /Перечень изменений запроса -- #}
  </div>
{% endblock tab_content_5 %}


{#----------------------------------------------------------------------------#}
{# Таб 6 — Статистика #}
{% block tab_content_6 %}
  {% set statistics_helper = project_manager.issue_statistics_helper %}

  {# -- История изменения состояний -- #}
    <div class="row mt-3">
      <div class="col-12 mb-2">
        <h5>История изменения состояний</h5>      
      </div>

      <div class="col-12">
        {# -- Перечень изменений состояний -- #}
          <table class="table table-striped table-bordered issue_field_table">
            <thead class="thead-dark">
              <tr>
                <th scope="col">Состояние</th>
                <th scope="col">Прогресс по состоянию</th>
                <th scope="col">Время нахождения в состоянии</th>
                <th scope="col">Инициатор состояния</th>
              </tr>
            </thead>
            <tbody>
              {% for issue_state in statistics_helper.issue_states_data(target_issue) %}
                {% set state = project_manager.state(issue_state.state_id) %}
                {% if state %}
                  <tr>
                    {#- Состояние -#}
                      <td>
                          {{ state.caption|e }}
                      </td>
                    {#- /Состояние -#}

                    {#- Прогресс по состоянию -#}
                      <td>
                        <div>
                          <div class="progress">
                            {% set progress = state.weight_percentage() %}
                            <div
                                class="progress-bar
                                  {%- if 100 == progress %} bg-success
                                  {%- elif 40 > progress %} bg-warning
                                  {%- endif %}"
                                role="progressbar"
                                style="width: {{ progress }}%;"
                                aria-valuenow="{{ progress }}"
                                aria-valuemin="0"
                                aria-valuemax="100">{{ progress }}%</div>
                          </div>
                        </div>
                      </td>
                    {#- /Прогресс по состоянию -#}

                    {#- Время нахождения в состоянии -#}
                      <td>
                        {{ project_manager.time_period(issue_state.timedelta) }}
                      </td>
                    {#- /Время нахождения в состоянии -#}

                    {#- Инициатор состояния -#}
                      <td>
                        {% set state_user = project_manager.user_by_id(issue_state.user_id) %}
                        {% if state_user %}
                          <a href="/users/user_statistics/{{ state_user.id }}">
                            {{ USER_NAME.VALUE_WITH_ICON(state_user, user.id) }}
                          </a>
                        {% endif %}
                      </td>
                    {#- /Инициатор состояния -#}
                  </tr>
                {% endif %}
              {% endfor %}
            </tbody>
          </table>
        {# -- /Перечень изменений состояний -- #}
      </div>
    </div>
  {# -- /История изменения состояний -- #}

  {# -- Трудозатраты -- #}
    <div class="row mt-3">
      <div class="col-12  mb-2">
        <h5>Трудозатраты</h5>      
      </div>

      <div class="col-12">
        <table class="table table-striped table-bordered issue_field_table">
          <thead class="thead-dark">
            <tr>
              <th scope="col">
                Сотрудник
                <br/>
                <small class="text-secondary">
                  (инициатор изменения состояния)
                </small>
              </th>
              <th scope="col">
                Затраченное время
                <br/>
                <small class="text-secondary">
                  (время нахождения в рабочем состоянии)
                </small>
              </th>
              <th scope="col">
                Вклад
                <br/>
                <small class="text-secondary">
                  (процент от общего затраченного времени)
                </small>
              </th>
            </tr>
          </thead>
          <tbody>
            {% for employee_time in statistics_helper.employee_time_data(target_issue) %}
              <tr>
                {#- Сотрудник -#}
                  <td>
                    {% set employee = project_manager.user_by_id(employee_time.employee_id) %}
                    {% if employee %}
                      <a href="/users/user_statistics/{{ employee_id }}">
                        {{ USER_NAME.VALUE_WITH_ICON(employee, user.id) }}
                      </a>
                    {% endif %}
                  </td>
                {#- /Сотрудник -#}

                {#- Затраченное время -#}
                  <td>
                    {{ project_manager.time_period(employee_time.timedelta) }}
                  </td>
                {#- /Затраченное время -#}

                {#- Вклад -#}
                  <td>
                    <div>
                      <div class="progress">
                        <div
                            class="progress-bar bg-info"
                            role="progressbar"
                            style="width: {{ employee_time.percentage }}%;"
                            aria-valuenow="{{ employee_time.percentage }}"
                            aria-valuemin="0"
                            aria-valuemax="100">{{ employee_time.percentage }}%</div>
                      </div>
                    </div>
                  </td>
                {#- /Вклад -#}

              </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  {# -- /Трудозатраты -- #}

{% endblock tab_content_6 %}


{#----------------------------------------------------------------------------#}
{% block scripts %}
  {{ ISSUES_TABLE.SCRIPTS() }}
  {{ FILE_INPUT.SCRIPTS() }}
  {{ MARKDOWN_TEXTAREA.SCRIPTS() }}
  {{ SELECT_OPTIONS.SCRIPTS() }}
{% endblock %}
